Ext.ns("org.cancerregulome.explorer.utils");

org.cancerregulome.explorer.utils.GoogleDriveClient = Ext.extend(Ext.util.Observable, {
    redirectUrl:null,
    taskRunner:null,

    constructor:function (config) {
        Ext.apply(this, config);

        org.cancerregulome.explorer.utils.GoogleDriveClient.superclass.constructor.call(this);

        this.addEvents("logged_in", "logged_out", "make_ready");

        this.on("make_ready", this.makeReady, this);

        var me = this;
        var runFn = function () {
            console.log("run");
            me.makeReady();
        };
        this.checkLoginTask = { run:runFn, interval:2000, repeat: 30 };
        this.taskRunner = new Ext.util.TaskRunner();
    },

    makeReady:function () {
        Ext.Ajax.request({
            url:"/google-drive-svc/",
            method:"GET",
            scope:this,
            success:function (o) {
                var json = Ext.util.JSON.decode(o.responseText);
                if (json.rejected) {
                    this.taskRunner.stopAll();
                }
                if (json.redirect) {
                    this.redirectUrl = json.redirect;
                    this.fireEvent("logged_out");
                } else if (json["client_id"]) {
                    this.redirectUrl = null;
                    this.taskRunner.stopAll();
                    this.fireEvent("logged_in", json);
                } else {
                    // TODO: Fire events
                }
            },
            failure:function (o, e) {
                // TODO : Fire events
            }
        });
    },

    login:function () {
        if (this.redirectUrl) {
            console.log("start running");
            this.taskRunner.start(this.checkLoginTask);

            window.open(this.redirectUrl, "_blank", "");
        } else {
            alert("cannot log you in, something weird is going on");
        }
    },

    logout:function () {
        Ext.Ajax.request({
            url:"/google-drive-svc/logout",
            method:"GET",
            scope:this,
            success:function () {
                this.fireEvent("make_ready");
            }
        });
    },

    writeSvgToPng: function(title, contents) {
        var fileMeta = {
            title:title,
            description: "Generated by Regulome Explorer: " + document.location,
            mimeType: "image/png",
            svgToPng: true
        };
        this.doPost(fileMeta, contents);
    },

    writeFile:function (title, contents, mimeType) {
        var fileMeta = {title:title, description: "Generated by Regulome Explorer: " + document.location};
        if (mimeType) {
            fileMeta["mimeType"] = mimeType;
            fileMeta["asGoogleDoc"] = true;
        }

        this.doPost(fileMeta, contents);
    },

    doPost: function(fileMeta, contents) {
        var title = fileMeta.title;
        if (!title) title = "RE_data_export";

        var loadingMsg = Ext.MessageBox.show({
            title: "Google Drive",
            msg: "Uploading '" + title + "'. Please wait a few moments...",
            icon: Ext.MessageBox.INFO
        });

        Ext.Ajax.request({
            url:"/google-drive-svc/",
            method:"POST",
            params:{
                meta:Ext.util.JSON.encode(fileMeta), content:contents
            },
            scope:this,
            success:function (o) {
                var json = Ext.util.JSON.decode(o.responseText);

                loadingMsg.hide();
                if (json && json.id) {
                    Ext.MessageBox.show({
                        title: "Google Drive",
                        msg: "Succesfully loaded '" + title + "'. <br/><br/><a href='http://drive.google.com' target='_blank'>Open Google Drive</a>",
                        buttons: Ext.MessageBox.OK,
                        icon: Ext.MessageBox.INFO
                    });
                }
            },
            failure:function () {
                loadingMsg.hide();
                Ext.MessageBox.show({
                    title: "Google Drive",
                    msg: "Failed to upload '" + title + "'.  Please try again.",
                    icon: Ext.MessageBox.WARNING,
                    buttons: Ext.MessageBox.OK
                });
            }
        });
    }
});

org.cancerregulome.explorer.utils.GetGoogleDriveMenu = function() {
    var googleDriveClient = new org.cancerregulome.explorer.utils.GoogleDriveClient({});
    var googleDriveLogin = new Ext.menu.Item({
        text: "Login to Google Profile",
        icon: "https://www.google.com/images/icons/ui/gprofile_button-64.png",
        handler: function() {
            alert("Not ready yet");
        }
    });

    var loggedInItems = [
        new Ext.menu.Item({
            text: "Spreadsheet",
            icon: "https://ssl.gstatic.com/docs/doclist/images/icon_10_spreadsheet_list.png",
            disabled: true,
            handler: function() {
                googleDriveClient.writeFile("RE_data_spreadsheet", org.cancerregulome.explorer.utils.RetrieveSpreadsheetContent(), "text/csv");
            }
        }),
        new Ext.menu.Item({
            text: 'Circular',
            disabled: true,
            menu: [
                {
                    text: 'SVG',
                    handler: function() {
                        googleDriveClient.writeFile("RE_circular_view.svg", retrieveSVG('circle-panel'));
                    }
                },
                {
                    text: 'PNG',
                    handler: function() {
                        googleDriveClient.writeSvgToPng("RE_circular_view.png", retrieveSVG('circle-panel'));
                    }
                }
            ]
        }),
        new Ext.menu.Item({
            text: 'Linear',
            disabled: true,
            menu: [
                {
                    text: 'SVG',
                    handler: function() {
                        googleDriveClient.writeFile("RE_linear_view.svg", retrieveSVG('linear-panel'));
                    }
                },
                {
                    text: 'PNG',
                    handler: function() {
                        googleDriveClient.writeSvgToPng("RE_linear_view.png", retrieveSVG('linear-panel'));
                    }
                }
            ]
        })
    ];

    googleDriveClient.on("logged_in", function(userProfile) {
        Ext.each(loggedInItems, function(lii) {
            lii.enable();
        });

        googleDriveLogin.setText("Log out " + userProfile.email);
        googleDriveLogin.setHandler(function() {
            googleDriveClient.logout();
        });
    });
    googleDriveClient.on("logged_out", function() {
        Ext.each(loggedInItems, function(lii) {
            lii.disable();
        });

        googleDriveLogin.setText("Login to Google Profile");
        googleDriveLogin.setHandler(function() {
            googleDriveClient.login();
        });
    });
    googleDriveClient.makeReady();

    var openGoogleDrive = {
        text: "Open Google Drive",
        icon: "https://developers.google.com/drive/images/drive_icon.png",
        handler: function() {
            window.open("http://drive.google.com", "_blank", "");
        }
    };

    return {
        text: 'Export to Google Drive',
        icon: "https://developers.google.com/drive/images/drive_icon.png",
        menu: [ googleDriveLogin, "-", openGoogleDrive, "-", loggedInItems ]
    }
};


org.cancerregulome.explorer.utils.RetrieveSpreadsheetContent = function() {
    var textdata = retrieveEdges();
    if (textdata) {
        var data = JSON.parse(textdata);
        if (data && data.length) {
            var text = "";
            Ext.each(data, function(row) {
                var rowdata = [];
                Ext.each(row, function(cell) {
                    rowdata.push("\"" + cell + "\"");
                });
                text += rowdata.join(",") + "\n";
            });
            return text;
        }
    }
    return null;
}
